package sd.qd.xiaoming.coffeedesk.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import sd.qd.xiaoming.coffeedesk.entity.CdDirectory;
import sd.qd.xiaoming.coffeedesk.service.CdDirectoryService;

@Controller
@RequestMapping("/directory")
public class CdDirectoryController {

    @Autowired
    private CdDirectoryService cdDirectoryService;
	
	@ResponseBody
    @RequestMapping("/delete_directory/{id}")
    public Object deleteDirectory(@PathVariable("id") final Long id) {
        Map<String, Object> result = new HashMap<String, Object>();
        this.cdDirectoryService.deleteById(id);
        result.put("success", true);
        return result;
    }
    @ResponseBody
    @RequestMapping("/get_directory_list")
	public Object getDirectoryList(@RequestParam(value="id",required=false) final Long pid){
	    List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
        List<CdDirectory> list = this.cdDirectoryService.findByPid(pid);
        for (CdDirectory d : list) {
            Map<String, Object> node = new HashMap<String, Object>();
            node.put("id", d.getId());
            node.put("text", d.getName());
            node.put("state", "closed");
            result.add(node);
        }
        return result;
	}

    @ResponseBody
    @RequestMapping("/new_directory")
    public Object newDirectory(@RequestParam("name") final String name,
            @RequestParam("pid") final Long pid) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (this.cdDirectoryService.isDirectoryExists(pid, name)) {
            result.put("success", false);
            result.put("msg", "文件夹已经存在！");
            return result;
        }
        CdDirectory dir = new CdDirectory();
        dir.setName(name);
        Date date = new Date();
        dir.setEditTime(date);
        dir.setParent(this.cdDirectoryService.findById(pid));
        this.cdDirectoryService.save(dir);
        result.put("success", true);
        return result;
    }
	
}
